package com.snxun.browser_light.module.home;

import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.lodz.android.corekt.utils.ToastUtils;
import com.lodz.android.pandora.base.fragment.LazyFragment;
import com.lodz.android.pandora.widget.base.ErrorLayout;
import com.lodz.android.pandora.widget.rv.drag.RecyclerViewDragHelper;
import com.snxun.browser_light.R;
import com.snxun.browser_light.adapter.fragment.AppRecyclerViewAdapter;
import com.snxun.browser_light.bean.AppInfoBean;
import com.snxun.browser_light.utils.DragCallbackHelper;
import com.snxun.browser_light.widget.eventbus.ChangeTitleEvent;
import com.snxun.browser_light.widget.eventbus.EventType;
import com.snxun.browser_light.widget.eventbus.MessageEvent;
import com.snxun.browser_light.widget.eventbus.ZoomEvent;
import com.snxun.browser_light.widget.webview.CustomPageWebView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;


/**
 * 展示网页的fragment
 * Created by Yangjw on 2020/11/20.
 */
public class WebViewFragment extends LazyFragment {

    /**
     * 获取APP信息列表的KEY
     */
    private static final String APP_LIST = "APP_LIST!";

    /**
     * 当前fragment唯一tag的KEY值
     */
    private static final String FRAGMENT_TAG_KEY = "FRAGMENT_TAG_KEY";
    /**
     * 当前fragment的唯一tag
     */
    private static String mFragmentTag;


    public static WebViewFragment newInstance(List<AppInfoBean> mList, String tag) {
        WebViewFragment fragment = new WebViewFragment();
        Bundle bundle = new Bundle();
        bundle.putParcelableArrayList(APP_LIST, (ArrayList<? extends Parcelable>) mList);
        bundle.putString(FRAGMENT_TAG_KEY, tag);
        fragment.setArguments(bundle);
        return fragment;
    }

    /**
     * 是否缩放标记，用于判断是否处于缩放状态
     */
    private static boolean mIsZoom;

    /**
     * 界面APP列表对应的RV
     */
    @BindView(R.id.fragment_rv)
    RecyclerView mAppRecyclerView;
    /**
     * 加载错误界面
     */
    @BindView(R.id.fragment_error_layout)
    ErrorLayout mErrorLayout;

    /**
     * webview
     */
    @BindView(R.id.fragment_webview)
    CustomPageWebView mWebView;

    /**
     * 顶部包含删除按钮的布局
     */
    @BindView(R.id.fragment_top_item_delete_layout)
    RelativeLayout mTopDeleteLayout;
    /**
     * 顶部删除按钮
     */
    @BindView(R.id.fragment_top_item_delete_img)
    ImageView mTopDeleteBtn;

    /**
     * fragment根布局
     */
    @BindView(R.id.fragment_root_layout)
    FrameLayout mRootLayout;

    /**
     * 透明的遮罩层
     */
    @BindView(R.id.fragment_shade_view)
    View mShadeView;
    /**
     * 拖拽帮助类
     */
    private RecyclerViewDragHelper<AppInfoBean> mDragHelper;

    /**
     * 应用列表适配器
     */
    private AppRecyclerViewAdapter mAdapter;

    /**
     * 模拟的数据源
     */
    private ArrayList<AppInfoBean> mList;

    /**
     * 退出间隔
     */
    private static final int EXIT_INTERVAL = 2000;

    /**
     * 退出时间
     */
    private long mExitTime = 0;


    @Override
    protected void startCreate() {
        super.startCreate();
        Bundle bundle = getArguments();
        if (bundle == null) {
            mList = new ArrayList<>();
        } else {
            mList = bundle.getParcelableArrayList(APP_LIST);
            mFragmentTag = bundle.getString(FRAGMENT_TAG_KEY);
        }

    }

    @Override
    protected int getAbsLayoutId() {
        return R.layout.fragment_webview;
    }

    @Override
    protected void findViews(@NotNull View view, @Nullable Bundle savedInstanceState) {
        super.findViews(view, savedInstanceState);
        ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        initWebView();
        initRecyclerView();
        initDeleteLayout();
    }

    /**
     * 初始化是否显示删除按钮布局
     */
    private void initDeleteLayout() {
        if (mIsZoom) {
            mTopDeleteLayout.setVisibility(View.VISIBLE);
        } else {
            mTopDeleteLayout.setVisibility(View.GONE);
        }
    }

    /**
     * 初始化webview
     */
    private void initWebView() {
        mWebView.setErrorLayout(mErrorLayout);
    }


    /**
     * 初始化应用列表
     */
    private void initRecyclerView() {
        GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 4);
        layoutManager.setOrientation(RecyclerView.VERTICAL);
        mAppRecyclerView.setLayoutManager(layoutManager);
        mAppRecyclerView.setHasFixedSize(true);
        mAdapter = new AppRecyclerViewAdapter(getContext());
        mAppRecyclerView.setAdapter(mAdapter);
        mDragHelper = new RecyclerViewDragHelper<AppInfoBean>(getContext());//实现可拖拽
        mDragHelper.setUseDrag(true).setSwipeEnabled(false);
        mDragHelper.build(mAppRecyclerView, mAdapter, new DragCallbackHelper<AppInfoBean>());
    }


    @Override
    protected void initData(@NotNull View view) {
        super.initData(view);

        mAdapter.setData(mList);
        mDragHelper.setList(mList);
        mAdapter.notifyDataSetChanged();
    }


    @Override
    protected void setListeners(@NotNull View view) {
        super.setListeners(view);

        /**
         * webview加载错误视图点击监听
         */
        mErrorLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mWebView.reload();
            }
        });

        /**
         * APP列表点击监听
         */
        mAdapter.setAppBtnClickListener(new AppRecyclerViewAdapter.AppListener() {
            @Override
            public void onClickAppBtnCallback(int position) {
                AppInfoBean bean = mList.get(position);
                mAppRecyclerView.setVisibility(View.GONE);
                mWebView.loadUrl(bean.appLoadUrl);
                mWebView.setVisibility(View.VISIBLE);
                EventBus.getDefault().post(new ChangeTitleEvent(bean));
            }
        });

        /**
         * 遮罩层触摸事件消费，避免点击事件穿透
         */
        mShadeView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (MotionEvent.ACTION_UP == event.getAction()) {
                    EventBus.getDefault().post(new ZoomEvent(EventType.FRAGMENT_RESTORE));
                }
                return true;
            }
        });
        /**
         * 右上角删除按钮点击事件
         */
        mTopDeleteBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().post(new MessageEvent(EventType.DELETE_SINGLE_FRAGMENT, mFragmentTag));
            }
        });
    }

    @Override
    public boolean onPressBack() {
        //如果遮罩层显示，表示当前为缩小状态，点击返回按钮则将缩小状态还原
        if (mShadeView.getVisibility() == View.VISIBLE) {
            EventBus.getDefault().post(new ZoomEvent(EventType.FRAGMENT_RESTORE));
        } else {
            if (mWebView.isCanGoBack()) {
                mWebView.goBack();
            } else if (mWebView.getVisibility() == View.VISIBLE) {
                mWebView.setVisibility(View.GONE);
                mAppRecyclerView.setVisibility(View.VISIBLE);
                AppInfoBean bean = new AppInfoBean();
                bean.appName = "主页";
                bean.appIconUrl=null;
                bean.appIconUri = Uri.fromFile(new File("src\\main\\res\\mipmap-xxhdpi\\app_icon.png"));
                EventBus.getDefault().post(new ChangeTitleEvent(bean));
            } else {
                if (System.currentTimeMillis() - mExitTime > EXIT_INTERVAL) {
                    ToastUtils.showShort(getContext(), R.string.main_exit_app);
                    mExitTime = System.currentTimeMillis();
                } else {
                    getActivity().finish();
                }
            }
        }
        return true;
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mWebView.release();
        EventBus.getDefault().unregister(this);
    }


    @RequiresApi(api = Build.VERSION_CODES.M)
    @Subscribe
    public void getEventMessage(MessageEvent event) {
        switch (event.getmEventType()) {
            case EventType
                    .SHOW_FRAGMENT_DELETE_BTN:
                mIsZoom = true;
                mTopDeleteLayout.setVisibility(View.VISIBLE);
                mShadeView.setVisibility(View.VISIBLE);
                break;
            case EventType.HIDE_FRAGMENT_DELETE_BTN:
                mIsZoom = false;
                mTopDeleteLayout.setVisibility(View.GONE);
                mShadeView.setVisibility(View.GONE);
                break;
            default:
                break;
        }
    }

    /**
     * 获取当前fragment的tag
     *
     * @return
     */
    public String getFragmentTag() {
        return mFragmentTag;
    }

    /**
     * 懒加载要关闭，否则关闭未加载fragment会空指针异常，因为根布局还没有初始化
     *
     * @return
     */
    @Override
    protected boolean configIsLazyLoad() {
        return false;
    }
}
